package com.my.interview.cocurrency;

import java.util.concurrent.RecursiveTask;

/**
 * Fork/Join 计算数据和
 * 把任务查分成足够小
 */
public class ForkJoinTask extends RecursiveTask<Long> {

    int start;
    int end;
    long [] array;
    static final int THRESHOLD = 100;


    public ForkJoinTask(int start, int end, long[] array) {
        this.start = start;
        this.end = end;
        this.array = array;
    }

    @Override
    protected Long compute() {

        //如果任务足够小，直接计算
        if(end - start <= THRESHOLD){
            long sum = 0;
            for(int i = start;i <= end;i++){
                sum += array[i];
            }
            try{
                Thread.sleep(1000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(String.format("compute %d~%d = %d",start, end, sum));
            return sum;
        }

        //任务太大，一分为2
        int middle = (start + end) / 2;
        System.out.println(String.format("split %d~%d ==> %d~%d, %d~%d", start, end, start, middle, middle, end));
        //创建相互独立的子任务
        ForkJoinTask subtask = new ForkJoinTask(start, middle, array);
        ForkJoinTask subtask2 = new ForkJoinTask(middle, end, array);
        //运行子任务
        invokeAll(subtask, subtask2);

        Long res1 = subtask.join();
        Long res2 = subtask2.join();

        Long res = res1 + res2;
        System.out.println("result = " + res1 + " + " + res2 + " ==> " + res);
        return res;
    }
}
